package com.bawei.shopping2

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.activity.viewModels
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.shopping2.databinding.ActivityLoginBinding
import com.bawei.shopping2.entity.UserEntity
import com.bawei.shopping2.http.ApiResponse
import com.bawei.shopping2.utils.ArouterPath
import com.bawei.shopping2.viewmodel.LoginViewModel
import com.blankj.utilcode.util.SPUtils
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
@AndroidEntryPoint
class LoginActivity : AppCompatActivity() {
    private lateinit var activityLoginBinding: ActivityLoginBinding
    private val loginViewModel:LoginViewModel by viewModels()
    private var job = Job()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityLoginBinding  = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(activityLoginBinding.root)

        activityLoginBinding.btLogin.setOnClickListener{
            var username = activityLoginBinding.etUsername.text.toString()
            var password = activityLoginBinding.etPassword.text.toString()
            var map = mutableMapOf<String,String>()
            map["username"] = username
            map["password"] = password
            var requestBody = map.toBody()

            CoroutineScope(job).launch(Dispatchers.Main) {
                var apiResponse = loginViewModel.login(requestBody)
                showLogin(apiResponse);
            }

        }
    }

    private fun showLogin(apiResponse: ApiResponse<UserEntity>) {
        if(apiResponse.code == 200){
            Toast.makeText(this,"登陆成功",Toast.LENGTH_LONG).show()
            SPUtils.getInstance().put("token",apiResponse.data.token)
            ARouter.getInstance()
                .build(ArouterPath.ROUTE_MAIN_PATH)
                .navigation()
            finish()
        }else{
            Toast.makeText(this,"登陆失败",Toast.LENGTH_LONG).show()
        }
    }
}